package net.lcheng.utils;

import java.util.Random;

/**
 * 主键生成工具（8位数字）
 * Created by LV on 2016/4/22 0022.
 * Email:LvLoveYuForever@gmail.com
 */
public class IdGenerator {

    private static final int LENGTH = 8;

    public static String generateNumber() {
        //初始化备选数组
        int[] defaultNums = new int[10];
        for (int i = 0; i < defaultNums.length; i++) {
            defaultNums[i] = i;
        }

        Random random = new Random();
        int[] nums = new int[LENGTH];
        //默认数组中可以选择的部分长度
        int canBeUsed = 10;
        //填充目标数组
        for (int i = 0; i < nums.length; i++) {
            //将随机选取的数字存入目标数组
            int index = random.nextInt(canBeUsed);
            nums[i] = defaultNums[index];
            //将已用过的数字扔到备选数组最后，并减小可选区域
            swap(index, canBeUsed - 1, defaultNums);
            canBeUsed--;
        }

        String tmp="";
        for (int k=0;k<nums.length;k++){
            tmp+=nums[k];
        }
        return tmp;
    }


    private static void swap(int i, int j, int[] nums) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
